package com.ncu.cloundeoffice.service.impl;

import com.ncu.cloundeoffice.mapper.TMenuMapper;
import com.ncu.cloundeoffice.pojo.ResponseResult;
import com.ncu.cloundeoffice.pojo.TAdmin;
import com.ncu.cloundeoffice.pojo.TMenu;
import com.ncu.cloundeoffice.service.TMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

@Service
public class TMenuServiceImpl implements TMenuService {

    @Autowired
    private TMenuMapper tMenuMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 通过用户id查询所有的菜单
     * @return
     */
    @Override
    public ResponseResult getMenuByAdminId() {
        int adminId = ((TAdmin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        ValueOperations<String,Object> valueOperations = redisTemplate.opsForValue();
        //从redis中取值
        List<TMenu> menuList = (List<TMenu>)valueOperations.get("menu_" + adminId);
        //如果redis的数据为空 从数据库中去取值
        if(CollectionUtils.isEmpty(menuList)){
            menuList = tMenuMapper.getMenuByAdminId(adminId);
            valueOperations.set("menu_"+adminId,menuList);
        }
        return ResponseResult.success("",menuList);


    }

    /**
     * 查询菜单所对应的所有权限
     * @return
     */
    @Override
    public List<TMenu> getMenuWithRole() {
        return tMenuMapper.getMenuWithRole();
    }

    /**
     * 查询所有的菜单
     * @return
     */
    @Override
    public List<TMenu> getAllMenus() {
        return tMenuMapper.getAllMenus();
    }


}
